import React from 'react';
import {
  View,
  Image,
  Platform,
  StyleSheet,
  NativeModules,
  findNodeHandle,
  requireNativeComponent
} from 'react-native';
import MediaControls, {PLAYER_STATES} from './controls';
import PropTypes from 'prop-types';

export default class ApsaraPlayer extends React.Component {
  static propTypes = {
    repeat: PropTypes.bool,
    muted: PropTypes.bool,
    volume: PropTypes.number,
    poster: PropTypes.string,
    autoPlay: PropTypes.bool,
    /* loop会自动且循环播放 */
    loop: PropTypes.bool,
    resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch']),
    source: PropTypes.shape({
      uri: PropTypes.string,
      sts: PropTypes.shape({
        vid: PropTypes.string,
        region: PropTypes.string,
        accessKeyId: PropTypes.string,
        accessKeySecret: PropTypes.string,
        securityToken: PropTypes.string
      }),
      auth: PropTypes.shape({
        vid: PropTypes.string,
        region: PropTypes.string,
        playAuth: PropTypes.string
      })
    }),
    onLoad: PropTypes.func,
    onSeek: PropTypes.func,
    onError: PropTypes.func,
    onProgress: PropTypes.func,
    onEnd: PropTypes.func
  };

  static defaultProps = {
    loop: false,
    autoPlay: false,
    resizeMode: 'cover'
  };

  constructor(props) {
    super(props);
    this.state = {
      currentTime: 0,
      duration: 0,
      isFullScreen: false,
      isLoading: true,
      paused: true,
      playerState: PLAYER_STATES.PAUSED
    };
  }

  get _module() {
    return Platform.OS === 'ios'
      ? NativeModules.ApsaraPlayerManager
      : NativeModules.ApsaraPlayerModule;
  }

  componentWillUnmount() {
    this._module.destroy(findNodeHandle(this._player));
  }

  setNativeProps(nativeProps) {
    this._player.setNativeProps(nativeProps);
  }

  seek = time => {
    if (isNaN(time)) {
      throw new Error('Specified time is not a number');
    }
    this.setNativeProps({seek: time});
  };

  _onLoad = event => {
    const {nativeEvent} = event;
    const {autoPlay} = this.props;

    this.setState({
      duration: nativeEvent.duration,
      isLoading: false,
      paused: autoPlay ? false : true,
      playerState: autoPlay ? PLAYER_STATES.PLAYING : PLAYER_STATES.PAUSED
    });
    if (this.props.onLoad) {
      this.props.onLoad(nativeEvent);
    }
  };

  _onError = event => {
    if (this.props.onError) {
      this.props.onError(event.nativeEvent);
    }
  };

  _onProgress = event => {
    const {isLoading, playerState} = this.state;
    if (!isLoading && playerState !== PLAYER_STATES.ENDED) {
      this.setState({currentTime: event.nativeEvent.currentTime});
    }
    if (this.props.onProgress) {
      this.props.onProgress(event.nativeEvent);
    }
  };

  _onSeek = event => {
    if (this.props.onSeek) {
      this.props.onSeek(event.nativeEvent);
    }
  };

  _onEnd = event => {
    if (this.props.loop) {
      return;
    }
    this.setState({playerState: PLAYER_STATES.ENDED, paused: true});
    if (this.props.onEnd) {
      this.props.onEnd(event.nativeEvent);
    }
  };

  onReplay = () => {
    this.seek(0);
    this.setState({playerState: PLAYER_STATES.PLAYING});
    this.setState({
      paused: false
    });
  };

  onPaused = playerState => {
    // console.log(this.state.paused);
    this.setState({
      paused: !this.state.paused,
      playerState
    });
  };

  save = options => {
    return this._module.save(options, findNodeHandle(this._player));
  };
  renderPoster() {
    const {poster} = this.props;
    if (this.state.isLoading && poster) {
      return (
        <Image
          style={styles.poster}
          resizeMode="cover"
          source={{uri: poster}}
        />
      );
    }
    return null;
  }

  renderMediaControls = () => {
    const {duration, isLoading, playerState, currentTime} = this.state;
    return (
      <MediaControls
        style={styles.mediaPlayer}
        duration={duration}
        isLoading={isLoading}
        mainColor="white"
        //   onFullScreen={this.onFullScreen}
        onPaused={this.onPaused}
        onReplay={this.onReplay}
        onSeek={this.seek}
        playerState={playerState}
        progress={currentTime}
        //  toolbar={this.renderToolbar()}
      />
    );
  };

  componentDidUpdate(prevProps) {
    // const {paused} = this.props;
    // // 当传入的type发生变化的时候，更新state
    // if (paused !== prevProps.paused) {
    //   this.setState({
    //     paused,
    //     playerState: paused ? PLAYER_STATES.PAUSED : PLAYER_STATES.PLAYING
    //   });
    // }
  }

  render() {
    const style = [styles.base, this.props.style];
    return (
      <View style={style}>
        <RNApsaraPlayer
          ref={r => {
            this._player = r;
          }}
          repeat={this.props.loop}
          resizeMode={this.props.resizeMode}
          style={StyleSheet.absoluteFill}
          source={this.props.source}
          paused={this.state.paused}
          onVideoLoad={this._onLoad}
          onVideoSeek={this._onSeek}
          onVideoError={this._onError}
          onVideoProgress={this._onProgress}
          onVideoEnd={this._onEnd}
        />
        {this.renderPoster()}
        {this.renderMediaControls()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden'
  },
  poster: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: '100%',
    height: '100%',
    zIndex: 100
  },
  mediaPlayer: {
    position: 'absolute',
    zIndex: 1011,
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
    backgroundColor: 'black'
  }
});

const RNApsaraPlayer = requireNativeComponent('ApsaraPlayer', ApsaraPlayer, {
  nativeOnly: {
    seek: true
  }
});
